<?php


namespace App\Services;

use Illuminate\Support\Facades\Cache;

class BaseTokenService
{
    /**
     * 生成 Token 字符串
     * @return string
     */
    public static function generateToken(): string
    {
        $randChars = getRandChar(32);
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        // salt 盐
        $salt = env('WX_TOKEN_SALT');
        // 用三组字符串，进行 md5 加密
        return md5($randChars . $timestamp . $salt);
    }

    /**
     * 根据 token 值里的某个变量的 key 获取对应的 value
     * @param $key
     * @return mixed
     * @throws \Exception
     */
    public static function getTokenVar($key): mixed
    {
        $token = request()->header('token');
        $vars = Cache::get($token);
        if (is_null($vars)) {
            throw new \Exception('Token 已过期或者无效 Token');
        } else {
            if (!is_array($vars)) {
                $vars = json_decode($vars, true);
            }

            if (array_key_exists($key, $vars)) {
                return $vars[$key];
            } else {
                throw new \Exception('尝试获取的 Token 变量并不存在');
            }
        }
    }

    /**
     * 获取用户的 uid
     * @return mixed
     * @throws \Exception
     */
    public static function getCurrentUid()
    {
        return self::getTokenVar('uid');
    }
}
